package net;

/**
 * Created by ytf on 2019/5/26 026.
 * Description:
 */
public class WatchDog
{
    private long mills;
    private boolean isOnRunning;
    private boolean isExit;
    private final WatchDog lock;
    private String name;

    public WatchDog(int seconds, String name)
    {
        mills = seconds * 1000;
        lock = this;
        this.name = name;
        isExit = false;
    }

    public WatchDog(float seconds, String name)
    {
        mills = (long) (seconds * 1000);
        lock = this;
        this.name = name;
        isExit = false;
    }

    public boolean isOnRunning()
    {
        return isOnRunning;
    }

    public void start(Callback callback)
    {
        if(isExit)
            return;

        if(!isOnRunning)
        {
            isOnRunning = true;

            new Thread()
            {
                @Override
                public void run()
                {
                    while (!isExit)
                    {
                        synchronized (lock)
                        {
                            try
                            {
//                                L.e("watch dog 进入等待");
                                lock.wait(mills);

                                if(isTouch)
                                {
                                    isTouch = false;
                                }else
                                {
                                    callback.onTimeout();
                                    isExit = true;
                                }
//                                L.e("watch dog 结束等待");
                            } catch (InterruptedException e)
                            {
                                isExit = true;
                            }
                        }
                    }
                    isOnRunning = false;
                }
            }.start();
        }
    }

    private boolean isTouch;
    public void touch()
    {
        if(isOnRunning)
        {
            synchronized (lock)
            {
                isTouch = true;
                lock.notify();
            }
        }
    }

    public void stop()
    {
        isOnRunning = false;
        isExit = true;
    }

    public interface Callback
    {
        void onTimeout();
    }

    @Override
    public String toString()
    {
        return name;
    }
}
